package com.sinping.qh.service.app.login.impl;

import com.sinping.qh.api.exception.HandlerException;
import com.sinping.qh.api.support.Const;
import com.sinping.qh.api.support.ConstEum;
import com.sinping.qh.api.support.ResDto;
import com.sinping.qh.domain.user.ContentInfo;
import com.sinping.qh.domain.user.TokenInfo;
import com.sinping.qh.domain.user.UserInfo;
import com.sinping.qh.domain.user.UserLaboratory;
import com.sinping.qh.dto.app.user.UserByAppDTO;
import com.sinping.qh.dto.mongo.auth.UserSessionDTO;
import com.sinping.qh.repository.mongo.user.ContentInfoRepository;
import com.sinping.qh.repository.mongo.user.UserInfoRepository;
import com.sinping.qh.repository.mongo.user.TokenRepository;
import com.sinping.qh.repository.mongo.user.UserLaboratoryRepository;
import com.sinping.qh.service.app.login.ILoginService;
import com.sinping.qh.service.app.auth.ISessionMongoService;
import com.sinping.qh.service.redis.RedisCommon;
import com.sinping.qh.service.redis.RedisService;
import com.sinping.qh.utils.mapper.JsonMapper;
import com.sinping.qh.utils.misc.IdGenerator;
import com.sinping.qh.utils.security.CryptoUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Base64Utils;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * @author zhangjin
 * @create 2018/5/30
 */
@Service
public class LoginServiceImpl implements ILoginService {

    @Autowired
    UserInfoRepository userInfoRepository;

    @Autowired
    UserLaboratoryRepository userLaboratoryRepository;

    @Autowired
    TokenRepository tokenRepository;

//    @Autowired
//    ISessionMongoService iSessionService;

    @Autowired
    RedisService redisService;

    @Autowired
    ContentInfoRepository contentInfoRepository;

    @Override
    public ResDto login(UserByAppDTO userByAppDTO) {

        ResDto resDto = new ResDto(ConstEum.SUCCESS);
        //判断密码是否正确
        UserInfo userInfo = userInfoRepository.findByUserName(userByAppDTO.getUsername());

        ContentInfo contentInfo=contentInfoRepository.findContentInfoByUserId(userInfo.getId());
        String saleStr="";
        if(contentInfo!=null){
            saleStr=contentInfo.getSalt();
        }
        else{
            throw new HandlerException(ConstEum.FAIL,"账号异常,请联系管理员");
        }

        byte[] salt= Base64Utils.decodeFromString(saleStr);

        if(!userInfo.getContent().equals(CryptoUtil.sha256(salt,userByAppDTO.getContent()))){
            throw new HandlerException(ConstEum.FAIL,"用户名或密码错误");
        }


        //创建token
        String token = "";
        TokenInfo tokenInfo = tokenRepository.findTokenInfoByUserId(userInfo.getId());
        if (tokenInfo == null) {
            tokenInfo=new TokenInfo();
            //保存token到数据库
            tokenInfo.setId(IdGenerator.uuid2().toString());
            token = IdGenerator.uuid2().toString();
            tokenInfo = new TokenInfo();
            tokenInfo.setToken(token);
            tokenInfo.setUserId(userInfo.getId());
            tokenInfo.setGmtCreated(new Date());
            tokenInfo.setGmtModified(new Date());
            tokenRepository.save(tokenInfo);
        } else {
            //更新用户的登录时间
            token = tokenInfo.getToken();
            tokenInfo.setGmtModified(new Date());
            tokenRepository.save(tokenInfo);
        }


//        UserSessionDTO userSessionDTO = iSessionService.createSessionByToken(token, userInfo);

        String ret =redisService.hgetByUserinfo(token);
//        int ret = iSessionService.saveSessionToRedis(userSessionDTO);
        if (StringUtils.isNotBlank(ret)) {
            resDto.setMsg("登录成功");
            resDto.setDatas(ret);
        } else {
            throw new HandlerException(ConstEum.FAIL,"登录失败");
        }
        return resDto;
    }

    @Override
    public UserSessionDTO getUserSessionDTO(HttpServletRequest request) {
        String token_name = Const.TOKEN_NAME;
//        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String token = request.getHeader(token_name);
        if (!StringUtils.isEmpty(token)) {
            String session =redisService.hgetByUserinfo(token);
            UserSessionDTO userSessionDTO = JsonMapper.defaultMapper().fromJson(session,UserSessionDTO.class);
            if (userSessionDTO != null) {
                return userSessionDTO;
            } else {
                return null;
            }
        } else {
            return null;
        }
    }

    @Override
    public ResDto logout(UserByAppDTO userByAppDTO) {
        ResDto resDto = new ResDto(ConstEum.SUCCESS);
//        UserSessionDTO userSessionDTO=
//                iSessionService.getSessionByToken(userByAppDTO.getToken());
        String key=RedisCommon.RedisPrimaryKey.UserSessionByApp.getFirstKey()+ userByAppDTO.getToken();
        redisService.expireKey(key);
        resDto.setMsg(ConstEum.SUCCESS.getMessage());
        return resDto;
    }
}
